package com.idopartx.phonelightning.utils

import android.app.Activity
import android.content.Context
import android.content.Context.INPUT_METHOD_SERVICE
import android.os.Handler
import android.os.Looper
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.core.content.ContextCompat.getSystemService

object DensityUtil {
    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    fun dip2px(context: Context, dpValue: Float): Int {
        val scale: Float = context.resources.displayMetrics.density
        return (dpValue * scale + 0.5f).toInt()
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    fun px2dip(context: Context, pxValue: Float): Int {
        val scale: Float = context.resources.displayMetrics.density
        return (pxValue / scale + 0.5f).toInt()
    }

    /**
     * 打开或者关闭输入法
     *
     * @param context
     * @param focusView 焦点View
     * @param hide      是否显示
     * @author LiuYuHang
     * @date 2014年9月28日
     */
    fun hidKeyBoard(context: Context, focusView: View?, hide: Boolean) {
        if (focusView == null) {
            return
        }
        val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        if (hide) {
            // 强制隐藏键盘
            imm?.hideSoftInputFromWindow(focusView.windowToken, 0)
        } else {
//            focusView.requestFocus();
//            imm.showSoftInput(focusView, InputMethodManager.SHOW_FORCED);
            if (focusView is EditText) {
                focusView.setSelection(0, focusView.length())
            }
            val handler = Handler(Looper.getMainLooper())
            handler.postDelayed({
                val inputManager =
                    focusView.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                inputManager?.showSoftInput(focusView, 0)
            }, 200)
        }
    }

    /**
     * 隐藏键盘
     */
    fun hideInput(context: Activity) {
        val imm = context.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
        val v = context.window.peekDecorView();
        if (null != v) {
            imm.hideSoftInputFromWindow(v.windowToken, 0);
        }
    }

}